package be.jabapage.snooker.service.importation.impl;

import java.io.Serializable;
import java.util.Map.Entry;

import org.apache.commons.lang.Validate;

import be.jabapage.snooker.container.TeamContainer;
import be.jabapage.snooker.exception.EntityNotFoundException;
import be.jabapage.snooker.exception.MultipleInstanceFoundException;
import be.jabapage.snooker.exception.ProcessingException;
import be.jabapage.snooker.jdo.administration.Player;
import be.jabapage.snooker.jdo.administration.Team;
import be.jabapage.snooker.service.administration.api.ITeamService;
import be.jabapage.snooker.service.importation.api.IPlayerImportService;
import be.jabapage.snooker.service.importation.api.ITeamImportService;
import be.jabapage.snooker.service.overwriter.api.ITeamOverwriter;

/**
 * @author axesq
 *
 */
public class TeamImportService implements ITeamImportService, Serializable {

	private static final long serialVersionUID = -3172759776347695374L;
	private final ITeamService teamService;
	private final IPlayerImportService playerImportService;
	private final ITeamOverwriter teamOverwriter;

	/**
	 * @param teamService
	 * @param playerImportService
	 * @param teamOverwriter
	 */
	public TeamImportService(final ITeamService teamService,
			final IPlayerImportService playerImportService,
			final ITeamOverwriter teamOverwriter) {
		Validate.notNull(teamService);
		Validate.notNull(playerImportService);
		Validate.notNull(teamOverwriter);
		this.teamService = teamService;
		this.playerImportService = playerImportService;
		this.teamOverwriter = teamOverwriter;
	}

	/**
	 * {@inheritDoc}
	 */
	public void importTeam(final TeamContainer container) throws ProcessingException {
		Validate.notNull(container);
		Team team = container.getTeam();
		Validate.notNull(team, "Team should be present in container");
		Validate.notNull(team.getName(), "Cann't import a team without a name.");

		try {
			Team dbTeam = teamService.retrieve(team.getName());
			teamOverwriter.overwrite(dbTeam, team);
			teamService.store(team);
		} catch (MultipleInstanceFoundException e) {
			throw new ProcessingException("Multiple teams found during import.", e);
		} catch (EntityNotFoundException e) {
			teamService.store(team);
		}

		//storing the players
		for (Entry<String, Player> playerEntry : container.getMembers().entrySet()) {
			Player player = playerEntry.getValue();
			player.setClubId(team.getClubId());
			player.setTeamId(team.getId());
			playerImportService.importPlayer(player);
		}
	}

}
